package deng.quartz;

import java.util.Arrays;
import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A scheduler service implemented with Quartz library.
 */
public class QuartzService
{
	/** A slf4j logger. */
	private static Logger logger = LoggerFactory.getLogger(QuartzService.class);
	
	private Scheduler scheduler;
	
	public void setScheduler(Scheduler scheduler)
	{
		this.scheduler = scheduler;
	}
	
	public void start()
	{
		logger.debug("Starting " + scheduler);
		try {
			scheduler.start();
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void stop()
	{
		logger.debug("Stopping " + scheduler);
		try {
			scheduler.shutdown();
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void addJob(String name, long delay)
	{
		Date startDate = new Date(System.currentTimeMillis() + delay);
		logger.debug("Adding job " + name + " that will start on " + startDate);
		
		try {
			JobDetail job = new JobDetail(name, SimpleJob.class);
			SimpleTrigger trigger = new SimpleTrigger(name, startDate);
			scheduler.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void deleteJob(String name)
	{
		logger.debug("Removing job " + name);
		try {
			// We will actually remove a trigger for this job.
			scheduler.unscheduleJob(name, Scheduler.DEFAULT_GROUP);
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}
	

	
	public void logAllTiggersAndJobs()
	{
		try {
			for (String groupName : scheduler.getTriggerGroupNames())
				logger.info("Triggers[" + groupName + "]=" + Arrays.asList(scheduler.getTriggerNames(groupName)));
			for (String groupName : scheduler.getJobGroupNames())
				logger.info("Jobs[" + groupName + "]=" + Arrays.asList(scheduler.getJobNames(groupName)));
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}
}
